import { useState } from 'react'
import { Plus, Bot, Calendar } from 'lucide-react'
import { taskAPI } from '../services/api'
import { getTodayString, getTomorrowString } from '../utils/timeUtils'

interface QuickTaskInputProps {
  onTaskCreated?: () => void
  placeholder?: string
  className?: string
}

export default function QuickTaskInput({ 
  onTaskCreated, 
  placeholder = "快速添加任务...",
  className = "" 
}: QuickTaskInputProps) {
  const [input, setInput] = useState('')
  const [isCreating, setIsCreating] = useState(false)
  const [showDateOptions, setShowDateOptions] = useState(false)
  const [selectedDate, setSelectedDate] = useState('')

  // 本地智能解析 - 使用统一时间工具
  const localSmartParse = (text: string) => {
    const result = {
      dueDate: null as string | null,
      dueTime: '' as string,
      priority: 'P2' as 'P0' | 'P1' | 'P2' | 'P3',
      category: 'work' as 'work' | 'personal' | 'learning' | 'health' | 'other'
    }
    
    // 时间解析
    const timeMatch = text.match(/(上午|下午|晚上|早上|中午)?\s*(\d{1,2})(点|时|:)\s*(半|(\d{1,2})(分?)|(\d{2}))?/)
    if (timeMatch) {
      const timePrefix = timeMatch[1]
      let hour = parseInt(timeMatch[2])
      let minute = 0
      
      if (timeMatch[4] === '半') {
        minute = 30
      } else if (timeMatch[5]) {
        minute = parseInt(timeMatch[5])
      } else if (timeMatch[7]) {
        minute = parseInt(timeMatch[7])
      }
      
      if (timePrefix === '下午' || timePrefix === '晚上') {
        if (hour < 12) hour += 12
      } else if (timePrefix === '上午' && hour === 12) {
        hour = 0
      }
      
      if (!timePrefix && hour < 8 && hour !== 0) {
        hour += 12
      }
      
      result.dueTime = `${hour.toString().padStart(2, '0')}:${minute.toString().padStart(2, '0')}`
      result.dueDate = getTodayString() // 使用统一的时间工具
    }
    
    // 日期解析 - 使用统一的时间工具
    if (/今天/.test(text)) {
      result.dueDate = getTodayString()
    } else if (/明天/.test(text)) {
      result.dueDate = getTomorrowString()
    }
    
    // 其他解析交给后端AI处理，保持快速输入的简洁性
    
    return result
  }

  const handleQuickCreate = async () => {
    if (!input.trim()) return
    
    setIsCreating(true)
    try {
      // 使用本地解析
      const parsedData = localSmartParse(input)
      
      // 如果有选择的日期，优先使用
      const finalDate = selectedDate || parsedData.dueDate
      
      // 合并日期和时间
      let fullDateTime = finalDate
      if (finalDate && parsedData.dueTime) {
        const [hours, minutes] = parsedData.dueTime.split(':').map(Number)
        const localDateTime = new Date(finalDate)
        localDateTime.setHours(hours, minutes, 0, 0)
        fullDateTime = localDateTime.toISOString()
      }
      
      const taskData = {
        title: input,
        description: '',
        dueDate: fullDateTime || undefined,
        reminderMinutes: 30,
        priority: parsedData.priority,
        category: parsedData.category,
        tags: [],
        notes: '',
        completed: false,
        subtasks: [],
        isRecurring: false,
        recurringType: null,
        recurringPattern: null,
        status: 'todo' as const,
        boardPosition: 0
      }
      
      const result = await taskAPI.createTask(taskData)
      if (result.id) {
        setInput('')
        setSelectedDate('')
        setShowDateOptions(false)
        onTaskCreated?.()
      }
    } catch (error) {
      console.error('快速创建任务失败:', error)
    } finally {
      setIsCreating(false)
    }
  }

  const handleKeyPress = (e: React.KeyboardEvent) => {
    if (e.key === 'Enter' && !e.shiftKey) {
      e.preventDefault()
      if (showDateOptions) {
        handleQuickCreate()
      } else if (input.trim()) {
        setShowDateOptions(true)
      }
    }
  }

  const setQuickDate = (type: 'today' | 'tomorrow' | 'week') => {
    const now = new Date()
    let targetDate = ''
    
    switch (type) {
      case 'today':
        targetDate = now.toISOString().split('T')[0]
        break
      case 'tomorrow':
        const tomorrow = new Date(now)
        tomorrow.setDate(now.getDate() + 1)
        targetDate = tomorrow.toISOString().split('T')[0]
        break
      case 'week':
        const nextWeek = new Date(now)
        nextWeek.setDate(now.getDate() + 7)
        targetDate = nextWeek.toISOString().split('T')[0]
        break
    }
    
    setSelectedDate(targetDate)
    handleQuickCreate()
  }

  return (
    <div className={`relative ${className}`}>
      <div className="flex items-center gap-2 p-3 bg-white border border-slate-200 rounded-xl shadow-sm hover:shadow-md transition-shadow">
        <Plus size={18} className="text-slate-400 flex-shrink-0" />
        <input
          type="text"
          value={input}
          onChange={(e) => setInput(e.target.value)}
          onKeyPress={handleKeyPress}
          placeholder={placeholder}
          className="flex-1 text-sm bg-transparent border-none outline-none placeholder-slate-400"
          disabled={isCreating}
        />
        {input.trim() && (
          <button
            onClick={() => setShowDateOptions(true)}
            className="p-1.5 text-blue-600 hover:bg-blue-50 rounded-lg transition-all"
            title="AI智能解析"
          >
            <Bot size={16} />
          </button>
        )}
      </div>

      {/* 快速日期选择 */}
      {showDateOptions && (
        <div className="absolute top-full left-0 right-0 mt-2 p-4 bg-white border border-slate-200 rounded-xl shadow-lg z-10">
          <div className="space-y-3">
            <div className="flex items-center gap-2 text-sm font-medium text-slate-700">
              <Calendar size={16} />
              选择截止时间
            </div>
            <div className="grid grid-cols-3 gap-2">
              <button
                onClick={() => setQuickDate('today')}
                className="px-3 py-2 text-sm bg-blue-50 text-blue-700 rounded-lg hover:bg-blue-100 transition-colors"
              >
                今天
              </button>
              <button
                onClick={() => setQuickDate('tomorrow')}
                className="px-3 py-2 text-sm bg-blue-50 text-blue-700 rounded-lg hover:bg-blue-100 transition-colors"
              >
                明天
              </button>
              <button
                onClick={() => setQuickDate('week')}
                className="px-3 py-2 text-sm bg-blue-50 text-blue-700 rounded-lg hover:bg-blue-100 transition-colors"
              >
                下周
              </button>
            </div>
            <div className="flex items-center gap-2 pt-2 border-t border-slate-100">
              <button
                onClick={handleQuickCreate}
                disabled={isCreating}
                className="flex-1 px-3 py-2 bg-blue-600 text-white text-sm rounded-lg hover:bg-blue-700 transition-colors disabled:opacity-50"
              >
                {isCreating ? '创建中...' : '创建任务'}
              </button>
              <button
                onClick={() => setShowDateOptions(false)}
                className="px-3 py-2 text-slate-500 text-sm rounded-lg hover:bg-slate-100 transition-colors"
              >
                取消
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  )
}
